import { defineStore } from 'pinia'
import { ref } from 'vue'
import { copyDeepObject } from '@/utils/index.js'
export const useBuyCarStores = defineStore('buyCarStores', () => {
  const buyCarList = ref([])

  //向购物车中添加数据
  const addProduct2ByCarList = (product) => {
    const index = getIndexFromArray(buyCarList.value, product)
    if (index > -1) {
      buyCarList.value[index].number++
    } else {
      //实现对象的深拷贝
      const newObj = copyDeepObject(product)
      newObj.number = 1
      buyCarList.value.push(newObj)
    }
  }

  //结算
  const payBuyCarList = () => {
    buyCarList.value = []
  }

  //返回数组中某个对象的索引
  const getIndexFromArray = (array, product) => {
    let index = -1
    array.forEach((item, i) => {
      if (item.id == product.id) {
        index = i
        return
      }
    })
    return index
  }
  return {
    buyCarList,
    addProduct2ByCarList,
    payBuyCarList
  }
})
